package ofpof.web.controller;

import javax.servlet.http.HttpServletResponse;

import ofpof.domain.User;
import ofpof.domain.dao.UserDao;
import ofpof.service.SecurityService;
import ofpof.service.UserService;
import ofpof.web.form.UserForm;
import ofpof.web.validator.UserFormValidator;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private UserFormValidator userFormValidator;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SecurityService securityService;
	
	@RequestMapping(value="/user/new",method = RequestMethod.GET)
	public ModelAndView newUser() {
		ModelAndView mav = new ModelAndView("newuser");
		mav.addObject("userForm",new UserForm());
		return mav;
	}
	
	@RequestMapping(value="/user/save",method=RequestMethod.POST)
	public String saveUser(@ModelAttribute("userForm") UserForm userForm, BindingResult bindingResult) {
		
		userFormValidator.validate(userForm, bindingResult);
		
		if (bindingResult.hasErrors()) {
			return "newuser";
		}
		
		userService.createNewUser(userForm);
		
		return "redirect:../user/created/" + userForm.getUser().getId().toString();
	}
	
	@RequestMapping("/user/created/{userId}")  
	public ModelAndView created(@PathVariable ObjectId userId) {
		User user = userDao.findById(userId);
		
		ModelAndView modelAndView = new ModelAndView("usercreated");
		modelAndView.addObject("user",user);
		return modelAndView;
	}
	
	@RequestMapping("/user/confirm/{userId}")
	public ModelAndView confirm(@PathVariable ObjectId userId,HttpServletResponse response) {
		User user = userDao.findById(userId);
		ModelAndView modelAndView = new ModelAndView("userconfirmed");
		modelAndView.addObject("user", user);
		
		if (user.isActive()) {
			modelAndView.addObject("status", 0);
			return modelAndView;
		}
		
		securityService.confirmUser(user,response);
		return modelAndView;
		
	}

	

}
